package com.myjoje.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.HashSet;
import java.util.Set;


public class CustomRealm extends AuthorizingRealm {

    /**
     * 授权
     *
     * @param principals
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        Set<String> permissions = getPermissionsFromDB();
        Set<String> roles = getRolesFromDB();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.setRoles(roles);
        authorizationInfo.setStringPermissions(permissions);
        return authorizationInfo;
    }

    private Set<String> getRolesFromDB() {
        Set<String> set = new HashSet<>();
        set.add("admin");
        set.add("root");
        return set;
    }

    private Set<String> getPermissionsFromDB() {
        Set<String> set = new HashSet<>();
        set.add("video:update");
        set.add("video:add");
        return set;
    }

    /**
     * 认证
     *
     * @param token
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        String username = (String) token.getPrincipal();
        String password = getPasswordFromDB();
        //安全框架帮忙校验
        return new SimpleAuthenticationInfo(username, password, this.getName());
    }

    private String getPasswordFromDB() {
        return "123";
    }
}
